package com.ccp.dev.extend.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.SystemConst;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.extend.service.ExtendSysOrgService;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.service.SysOrgService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 扩展的组织管理controller
 *
 * @author 创新中心-王明亮
 */
@Controller
@Action(ownermodel = SysAuditModelType.ORG_MANAGEMENT)
@RequestMapping(UrlConstants.PROJECT_ROOT + "/extend/sysOrg")
public class ExtendSysOrgController extends SysBaseController {

    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private ExtendSysOrgService extendSysOrgService;

    /**
     * 查找租户组织list树
     *
     * @param request 请求
     * @return ResultData
     */
    @Action(description = "查询租户组织列表", detail = "查询列表<#if success>成功<#else>失败</#if>", exectype = "查询日志")
    @GetMapping("/tenTreeList")
    @ResponseBody
    public ResultData tenTreeList(HttpServletRequest request) {
        try {
            /*
             1.查找当前用户所属机构（租户|组织） 根据登录人的租户ID去展示组织树
             */
            String userId = ContextUtil.getCurrentUserId();
            List<SysOrg> sysOrgList = null;
            /*
            超管的用户id是初始化入库的 所有超管id被视为常量
             */
            if (SystemConst.SUPER_ADMIN_ID.equals(userId)) {
                sysOrgList = sysOrgService.querySubSysOrgTreeDataBySupOrgId(SystemConst.TOP_ORG_ID);
                // sysOrgList 是所有子组织树，把租户筛选出来
                sysOrgList.removeIf(sysOrg -> sysOrg.getIsTenant() != 1);
            } else {
                String belongOrgId = extendSysOrgService.getTenOrg(userId) != null ? extendSysOrgService.getTenOrg(userId).getOrgId() : SystemConst.TOP_ORG_ID;
                sysOrgList = sysOrgService.querySysOrgTreeDataByOrgId(belongOrgId);
                // sysOrgList 是所有子组织树，把租户筛选出来
                sysOrgList.removeIf(sysOrg -> sysOrg.getIsTenant() != 1);
            }
            int count = sysOrgList == null ? 0 : sysOrgList.size();
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success", count, sysOrgList);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

}
